package com.roy.DubboRPCDemo.util;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.roy.DubboRPCDemo.anno.ServiceExe;

import scala.Tuple2;

public class ExecutorManager {
private static Logger logger = LoggerFactory.getLogger(ExecutorManager.class);
	
	private static Map<String,Tuple2<Object, Method>> allMethods = new HashMap<>();
	static {
		Reflections reflection = new Reflections("com.roy.DubboRPCDemo.executor",new MethodAnnotationsScanner());
		Set<Method> methods = reflection.getMethodsAnnotatedWith(ServiceExe.class);
		methods.stream().forEach(method-> {
			Class<?> cls = method.getDeclaringClass();
			String clsName = cls.getName();
			ServiceExe anno = method.getAnnotation(ServiceExe.class);
			Object obj;
			try {
				obj = cls.newInstance();
				allMethods.put(anno.exeId(), new Tuple2<Object, Method>(obj,method));
				logger.info("load executor id: {} ,method: {} succed",anno.exeId(), clsName + "."+method.getName());
			} catch (Exception e) {
				logger.info("init Object of " + clsName + "failed;reason = " + e.getMessage());
			}
		});
	}
	
	public static Tuple2<Object, Method> getMethod(String exeId) {
		return allMethods.containsKey(exeId)?allMethods.get(exeId):null;
	}
}
